package com.dqp.cslggroup.JWXT;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewStub;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import androidx.appcompat.widget.Toolbar;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.dqp.cslggroup.Api.jwxtApi;
import com.dqp.cslggroup.Api.xxmhApi;
import com.dqp.cslggroup.EventBus.MessageEvent;
import com.dqp.cslggroup.Features.Setting;
import com.dqp.cslggroup.R;
import com.dqp.cslggroup.UI.AlertDialog;
import com.dqp.cslggroup.UI.BaseActivity;
import com.dqp.cslggroup.UI.DialogView;
import com.dqp.cslggroup.UI.GradeAdapter;
import com.dqp.cslggroup.Util.*;
import com.dqp.cslggroup.bean.Grade;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SearchGrades extends BaseActivity {
    private Spinner cx_spinner_year, cx_spinner_term;
    private Button cx_button;
    private int cx_year, cx_term;
    private String cx_year_str, cx_term_str;
    private Map<String, String> cx_grade_cookies;
    private String stuNum, use_url;
    private ListView listView;
    private ViewStub viewstub_loading;
    ExecutorService threadPool = Executors.newFixedThreadPool(2);

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inquire);
        EventBus.getDefault().register(this);
        Toolbar toolbar = findViewById(R.id.include_toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        stuNum = SharedPreferencesUtil.getStringSp(this, "stuNum", null);
        initCmp();
        getCookies();
        cx_Grade();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    public void getCookies() {
//        List list = MyApplication.getDaoInstant().getStudentDao().queryBuilder().where(studentDao.Properties.Xh.eq(stuNum)).build().list();
//        if (list.size() > 0) return;
        Map<String, String> map = SharedPreferencesUtil.getMap(this, "cookies");
        long time = SharedPreferencesUtil.getLongSp(this, "cookiesTime", 0);
        long nowTime = GetTimeUtil.getCurrentTimeMillis();
        long x = GetTimeUtil.minuteDifference(nowTime, time);
        if (x < 10) {
            cx_grade_cookies = map;

        } else {
            String xxmh = SharedPreferencesUtil.getStringSp(this, "password_XXMH", null);
            String sno = SharedPreferencesUtil.getStringSp(this, "stuNum", null);
            String jwxt = SharedPreferencesUtil.getStringSp(this, "password_JWXT", null);
            if (!StringUtil.isEmpty(xxmh, sno, jwxt)) {
                viewstub_loading.setVisibility(View.VISIBLE);
                threadPool.execute(() -> {
                    JSONObject jsonObject = xxmhApi.login(sno, xxmh, "0");
                    if (Result.jsonResultIsTure(jsonObject)) {
                        JSONObject object = jsonObject.getJSONObject("info");
                        Map<String, String> xxmhCookies = JSONObject.parseObject(object.toJSONString(), new TypeReference<Map<String, String>>() {
                        });
                        if (xxmhCookies == null || xxmhCookies.size() < 2) return;
                        object = jwxtApi.login(xxmhCookies, sno, jwxt, "0");
                        if (Result.jsonResultIsTure(object)) {
                            cx_grade_cookies = xxmhCookies;
                            CookiesUtil.save(this, cx_grade_cookies);
                            EventBus.getDefault().post(new MessageEvent("JWXT_main", 12, null));
                        }
                    } else if (jsonObject.containsKey("resultMsg") && jsonObject.getJSONObject("resultMsg").containsKey("密码错误")) {
                        alertDialog("密码错误", "您绑定的信息门户账号密码错误，您近期是否进行了密码更改？" +
                                "现已无法正常使用该模块功能，为确保正常使用请前往设置重新绑定！");
                    }
                });
            } else {
                alertDialog("账号未绑定", "检测到您绑定的信息门户、教务系统账号或密码信息缺失，无法正常使用该模块功能，" +
                        "为确保正常使用请前往设置进行绑定！");
            }
        }
    }

    public void alertDialog(String title, String msg) {
        AlertDialog alertDialog = new AlertDialog(this);
        alertDialog.builder();
        alertDialog.setGone()
                .setTitle(title)
                .setMsg(msg)
                .setMsgGravity(false)
                .setNegativeButton("设置", R.color.colorAccent, v1 -> {
                    alertDialog.dismiss();
                    UiUtils.startActivity(this, Setting.class);
                })
                .setPositiveButton("取消", R.color.colorAccent, v2 -> {
                    alertDialog.dismiss();
                    finish();
                })
                .show();
    }

    private void initCmp() {
        cx_spinner_term = findViewById(R.id.cx_spinner_term);
        cx_spinner_year = findViewById(R.id.cx_spinner_year);
        cx_button = findViewById(R.id.cx_button);
        listView = findViewById(R.id.cx_list);
        viewstub_loading = findViewById(R.id.viewstub_loading);
        int month = GetTimeUtil.getMonth();
        int year = GetTimeUtil.getYear();
        if (month < 8 && month >= 2) {
            cx_spinner_year.setSelection(year - 2017);
            cx_spinner_term.setSelection(1);
        } else {
            if (month > 7) year++;
            cx_spinner_year.setSelection(year - 2017);
            cx_spinner_term.setSelection(0);
        }
    }

    @SuppressLint("HandlerLeak")
    private void cx_Grade() {

        cx_button.setOnClickListener(view -> {
            listView.setAdapter(null);
            EventBus.getDefault().post(new MessageEvent("SearchGrades", 2, null));
            threadPool.execute(() -> {
                try {
                    cx_year_str = cx_spinner_year.getSelectedItem().toString();
                    cx_term_str = cx_spinner_term.getSelectedItem().toString();
                    int[] arr_year = StringUtil.SelectNumber(cx_year_str);
                    cx_year = arr_year[0];
                    int[] arr_term = StringUtil.SelectNumber(cx_term_str);
                    cx_term = arr_term[0];
                    JSONObject jsonObject = jwxtApi.getGrades(stuNum, cx_year, cx_term, cx_grade_cookies);
                    if (Result.jsonResultIsTure(jsonObject)) {
                        if (jsonObject.containsKey("details")) {
                            jsonObject = jsonObject.getJSONObject("details");
                            if (!jsonObject.containsKey("score")) return;
                            String jsonObjectString = jsonObject.getString("score");
                            JSONArray array = JSONArray.parseArray(jsonObjectString);
                            List<Grade> grades = new ArrayList<>();
                            for (Object o : array) {
                                JSONObject object = (JSONObject) o;
                                Grade grade = object.toJavaObject(Grade.class);
                                grades.add(grade);
                            }
                            EventBus.getDefault().post(new MessageEvent("SearchGrades", 1, grades));
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    EventBus.getDefault().post(new MessageEvent("SearchGrades", 4, null));
                }
            });
        });
    }

    private void initList(List<Grade> gradeList) {
        if (gradeList == null || gradeList.size() == 0) {
            ToastUtil.showToast("😁目前还未公布考试成绩哦！");
        } else {
            GradeAdapter gradeAdapte = new GradeAdapter(gradeList, this);
            listView.setAdapter(gradeAdapte);
//            EventBus.getDefault().post(new MessageEvent("SearchGrades", 3, gradeList));
//            listView.setOnItemClickListener((adapterView, view, i, l) -> {
//                EventBus.getDefault().post(new MessageEvent("SearchGrades", 2, null));
//                Grade grade = gradeList.get(i);
//                getMore(grade);
//            });
        }

    }


    public void getMore(Grade grade) {
        new Thread(() -> {
            GetStudentGrade getStudentGrade = new GetStudentGrade(use_url, cx_year, cx_term, cx_grade_cookies, stuNum);
            try {
                String x = getStudentGrade.getGradeMore(grade.getJxb_id(), grade.getXnm(), grade.getXqm(), grade.getCname());
                EventBus.getDefault().post(new MessageEvent("SearchGrades", 6, x));
            } catch (Exception e) {
                e.printStackTrace();
                EventBus.getDefault().post(new MessageEvent("SearchGrades", 7, null));

            }
        }).start();
    }

    private void showMore(String msg) {
        msg = msg.replace(" 【", "").replace("】 ", "").replace("【", "").replace("】", "");
        ArrayList<Grade> dataList = new ArrayList<>();
        String[] grades = msg.split(" ");
        for (int i = 1; i < grades.length - 2; i = i + 3) {
            Grade grade = new Grade();
            grade.setFx(grades[i].replace(" ", ""));
            grade.setBl(grades[i + 1].replace(" ", ""));
            grade.setCj(grades[i + 2].replace(" ", ""));
            dataList.add(grade);
        }
        DialogView.gradeMore(this, dataList);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getEvent().equals("SearchGrades")) {
            switch (event.getWhat()) {
                case 1:
                    viewstub_loading.setVisibility(View.GONE);
                    initList((List<Grade>) event.getObj());
                    break;
                case 2:
                    viewstub_loading.setVisibility(View.VISIBLE);
                    break;
                case 3:
                    viewstub_loading.setVisibility(View.GONE);
                    break;
                case 4:
                    viewstub_loading.setVisibility(View.GONE);
                    ToastUtil.showToast("🤦网络异常");

                    break;
                case 5:
                    viewstub_loading.setVisibility(View.GONE);
                    ToastUtil.showToast("🤦数据异常");
                    break;
                case 7:
                    viewstub_loading.setVisibility(View.GONE);
                    ToastUtil.showToast("🤦哇哦数据跑丢了");
                    break;
                case 6:
                    viewstub_loading.setVisibility(View.GONE);
                    String x = event.getMessage();
                    showMore(x);
                    break;
            }
        }
    }
}



